<template>
  <a-form
    ref="loginForm"
    :model="userInfo"
    class="login-form"
    layout="vertical"
    @submit="handleSubmit"
  >
    <a-form-item
      field="username"
      :rules="[{ required: true, message: $t('login.form.userName.errMsg') }]"
      :validate-trigger="['change', 'blur']"
      hide-label
    >
      <a-input
        v-model="userInfo.username"
        :placeholder="$t('login.form.userName.placeholder')"
      >
        <template #prefix>
          <icon-user />
        </template>
      </a-input>
    </a-form-item>
    <a-form-item
      field="password"
      :rules="[{ required: true, message: $t('login.form.password.errMsg') }]"
      :validate-trigger="['change', 'blur']"
      hide-label
    >
      <a-input-password
        v-model="userInfo.password"
        :placeholder="$t('login.form.password.placeholder')"
        allow-clear
      >
        <template #prefix>
          <icon-lock />
        </template>
      </a-input-password>
    </a-form-item>
    <a-space :size="16" direction="vertical">
      <div class="login-form-password-actions">
        <a-checkbox
          checked="rememberPassword"
          :model-value="loginConfig.rememberPassword"
          @change="setRememberPassword as any"
        >
          {{ $t('login.form.rememberPassword') }}
        </a-checkbox>
        <a-link @click="changeLogin(LoginMethods.forget)">{{
          $t('login.form.forgetPassword')
        }}</a-link>
      </div>
      <a-button type="primary" html-type="submit" long :loading="loading">
        {{ $t('login.form.login') }}
      </a-button>
    </a-space>
  </a-form>
</template>

<script setup lang="ts">
  import { reactive } from 'vue';
  import { useRouter } from 'vue-router';
  import { Message } from '@arco-design/web-vue';
  import { ValidatedError } from '@arco-design/web-vue/es/form/interface';
  import { useI18n } from 'vue-i18n';
  import { useStorage } from '@vueuse/core';
  import { useUserStore } from '@/store';
  import useLoading from '@/hooks/loading';
  import type { LoginData } from '@/api/user';
  import pwdEncrypt from '@/utils/encryption/pwd';
  import { dotToSlash } from '@/utils/index';
  import LoginMethods from '../constant';

  const emit = defineEmits(['changeLogin']);

  const changeLogin = (method: LoginMethods) => {
    emit('changeLogin', method);
  };

  const router = useRouter();
  const { t } = useI18n();
  const { loading, setLoading } = useLoading();
  const userStore = useUserStore();

  const loginConfig = useStorage('login-config', {
    // TODO: 上线前去掉默认值
    rememberPassword: true,
    username: 'fawkes',
    password: 'OWndZi1mKZdC',
  });
  const userInfo = reactive({
    username: loginConfig.value.username,
    password: loginConfig.value.password,
  });

  const handleSubmit = async ({
    errors,
    values,
  }: {
    errors: Record<string, ValidatedError> | undefined;
    values: Record<string, any>;
  }) => {
    if (loading.value) return;
    if (!errors) {
      setLoading(true);
      try {
        const { username, password } = values;
        const data = {
          username,
          password: pwdEncrypt(password),
          grant_type: 'password',
        };
        await userStore.login(data as LoginData);
        const { redirect, ...othersQuery } = router.currentRoute.value.query;
        router.push({
          path: dotToSlash(redirect as string) || '/dashboard',
          query: {
            ...othersQuery,
          },
        });
        Message.success(t('login.form.login.success'));
        const { rememberPassword } = loginConfig.value;
        loginConfig.value.username = rememberPassword ? username : '';
        loginConfig.value.password = rememberPassword ? password : '';
      } catch (err) {
        Message.error(`${err}`);
      } finally {
        setLoading(false);
      }
    }
  };
  const setRememberPassword = (value: boolean) => {
    loginConfig.value.rememberPassword = value;
  };
</script>

<script lang="ts">
  export default {
    name: 'AccountForm',
  };
</script>

<style lang="less" scoped></style>
